"""
潜力预测专家智能体
基于AI模型预测候选人的职业发展潜力和成长轨迹
"""

import asyncio
import json
import numpy as np
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass

from ...core.interfaces import AgentInterface, Task, TaskStatus, ToolInterface
from ...core.container import container


@dataclass
class PotentialDimension:
    """潜力维度数据类"""
    name: str
    score: float
    weight: float
    description: str
    indicators: List[str]


@dataclass
class CareerTrajectory:
    """职业轨迹数据类"""
    timeline: str
    predicted_role: str
    probability: float
    key_milestones: List[str]
    required_skills: List[str]


class PotentialPredictionTool(ToolInterface):
    """潜力预测工具"""
    
    def __init__(self):
        self.name = "potential_predictor"
        self.description = "Predict candidate potential and career growth trajectory using AI models"
        
        # 初始化预测模型参数
        self.dimension_weights = {
            "learning_ability": 0.25,
            "adaptability": 0.20,
            "leadership_potential": 0.15,
            "technical_depth": 0.20,
            "innovation_capacity": 0.10,
            "collaboration_skills": 0.10
        }
        
        # 职业发展路径模板
        self.career_paths = {
            "technical_expert": {
                "title": "技术专家路径",
                "milestones": ["高级工程师", "技术专家", "首席架构师"],
                "required_skills": ["深度技术专长", "系统设计能力", "技术前瞻性"]
            },
            "tech_leader": {
                "title": "技术管理路径", 
                "milestones": ["技术Lead", "技术经理", "技术总监"],
                "required_skills": ["团队管理", "技术决策", "业务理解"]
            },
            "product_oriented": {
                "title": "产品技术路径",
                "milestones": ["产品工程师", "产品技术专家", "产品技术总监"],
                "required_skills": ["产品思维", "用户体验", "商业敏感"]
            },
            "innovation_driver": {
                "title": "创新驱动路径",
                "milestones": ["研发工程师", "创新专家", "首席科学家"],
                "required_skills": ["研究能力", "创新思维", "技术洞察"]
            }
        }
    
    async def execute(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """执行潜力预测"""
        candidate_data = parameters.get("candidate_data", {})
        prediction_timeframe = parameters.get("timeframe", "medium_term")  # short, medium, long
        focus_areas = parameters.get("focus_areas", ["all"])
        
        if not candidate_data:
            return {"error": "No candidate data provided"}
        
        try:
            # 1. 多维度潜力分析
            potential_dimensions = await self._analyze_potential_dimensions(candidate_data)
            
            # 2. 职业轨迹预测
            career_trajectories = await self._predict_career_trajectories(
                candidate_data, potential_dimensions, prediction_timeframe
            )
            
            # 3. 成长速度预测
            growth_prediction = await self._predict_growth_speed(candidate_data, potential_dimensions)
            
            # 4. 风险因素分析
            risk_factors = await self._analyze_risk_factors(candidate_data)
            
            # 5. 发展建议生成
            development_recommendations = await self._generate_development_recommendations(
                potential_dimensions, career_trajectories
            )
            
            # 6. 综合潜力评分
            overall_potential = await self._calculate_overall_potential(potential_dimensions)
            
            result = {
                "candidate_id": candidate_data.get("id", "unknown"),
                "prediction_timestamp": datetime.now().isoformat(),
                "timeframe": prediction_timeframe,
                "overall_potential": overall_potential,
                "potential_dimensions": [dim.__dict__ for dim in potential_dimensions],
                "career_trajectories": [traj.__dict__ for traj in career_trajectories],
                "growth_prediction": growth_prediction,
                "risk_factors": risk_factors,
                "development_recommendations": development_recommendations,
                "confidence_level": await self._calculate_confidence_level(candidate_data)
            }
            
            return result
            
        except Exception as e:
            return {"error": f"Potential prediction failed: {str(e)}"}
    
    async def _analyze_potential_dimensions(self, candidate_data: Dict[str, Any]) -> List[PotentialDimension]:
        """分析潜力维度"""
        dimensions = []
        
        # 1. 学习能力分析
        learning_ability = await self._assess_learning_ability(candidate_data)
        dimensions.append(PotentialDimension(
            name="learning_ability",
            score=learning_ability["score"],
            weight=self.dimension_weights["learning_ability"],
            description="学习新技术和适应变化的能力",
            indicators=learning_ability["indicators"]
        ))
        
        # 2. 适应性分析
        adaptability = await self._assess_adaptability(candidate_data)
        dimensions.append(PotentialDimension(
            name="adaptability",
            score=adaptability["score"],
            weight=self.dimension_weights["adaptability"],
            description="适应不同环境和挑战的能力",
            indicators=adaptability["indicators"]
        ))
        
        # 3. 领导潜力分析
        leadership_potential = await self._assess_leadership_potential(candidate_data)
        dimensions.append(PotentialDimension(
            name="leadership_potential",
            score=leadership_potential["score"],
            weight=self.dimension_weights["leadership_potential"],
            description="领导团队和推动项目的潜在能力",
            indicators=leadership_potential["indicators"]
        ))
        
        # 4. 技术深度分析
        technical_depth = await self._assess_technical_depth(candidate_data)
        dimensions.append(PotentialDimension(
            name="technical_depth",
            score=technical_depth["score"],
            weight=self.dimension_weights["technical_depth"],
            description="深入钻研技术的能力和潜力",
            indicators=technical_depth["indicators"]
        ))
        
        # 5. 创新能力分析
        innovation_capacity = await self._assess_innovation_capacity(candidate_data)
        dimensions.append(PotentialDimension(
            name="innovation_capacity",
            score=innovation_capacity["score"],
            weight=self.dimension_weights["innovation_capacity"],
            description="创新思维和解决问题的创造性",
            indicators=innovation_capacity["indicators"]
        ))
        
        # 6. 协作能力分析
        collaboration_skills = await self._assess_collaboration_skills(candidate_data)
        dimensions.append(PotentialDimension(
            name="collaboration_skills",
            score=collaboration_skills["score"],
            weight=self.dimension_weights["collaboration_skills"],
            description="团队协作和沟通的能力",
            indicators=collaboration_skills["indicators"]
        ))
        
        return dimensions
    
    async def _assess_learning_ability(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估学习能力"""
        score = 0.0
        indicators = []
        
        # 基于教育背景
        education = candidate_data.get("education", "")
        if "硕士" in education or "Master" in education:
            score += 0.2
            indicators.append("具有高等教育背景")
        elif "本科" in education or "Bachelor" in education:
            score += 0.15
            indicators.append("具有本科教育背景")
        
        # 基于技能多样性
        skills = candidate_data.get("skills", [])
        if len(skills) > 10:
            score += 0.3
            indicators.append("技能面广泛，学习能力强")
        elif len(skills) > 5:
            score += 0.2
            indicators.append("掌握多项技能")
        
        # 基于工作经验中的技术更新
        experience_text = candidate_data.get("experience", "")
        modern_tech_keywords = ["AI", "机器学习", "微服务", "云计算", "React", "Vue", "Docker", "Kubernetes"]
        modern_tech_count = sum(1 for keyword in modern_tech_keywords if keyword in experience_text)
        
        if modern_tech_count >= 3:
            score += 0.25
            indicators.append("紧跟技术发展趋势")
        elif modern_tech_count >= 1:
            score += 0.15
            indicators.append("接触过现代技术栈")
        
        # 基于项目复杂度
        if "架构" in experience_text or "设计" in experience_text:
            score += 0.15
            indicators.append("参与过系统架构设计")
        
        # 基于学习证据
        if "认证" in candidate_data.get("certifications", "") or "证书" in candidate_data.get("certifications", ""):
            score += 0.1
            indicators.append("主动获取专业认证")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _assess_adaptability(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估适应性"""
        score = 0.0
        indicators = []
        
        # 基于工作经历多样性
        experience_text = candidate_data.get("experience", "")
        companies = candidate_data.get("companies", [])
        
        if len(companies) >= 3:
            score += 0.3
            indicators.append("具有多家公司工作经验")
        elif len(companies) >= 2:
            score += 0.2
            indicators.append("有换工作适应经验")
        
        # 基于行业经验
        industries = ["互联网", "金融", "教育", "医疗", "电商", "游戏"]
        industry_count = sum(1 for industry in industries if industry in experience_text)
        
        if industry_count >= 2:
            score += 0.2
            indicators.append("跨行业工作经验")
        
        # 基于技术栈变化
        if "转型" in experience_text or "学习" in experience_text:
            score += 0.15
            indicators.append("主动技术转型经历")
        
        # 基于项目类型多样性
        project_types = ["Web", "移动", "后端", "前端", "全栈", "数据", "AI"]
        project_diversity = sum(1 for ptype in project_types if ptype in experience_text)
        
        if project_diversity >= 3:
            score += 0.2
            indicators.append("项目类型经验丰富")
        
        # 基于地理流动性
        locations = candidate_data.get("locations", [])
        if len(locations) >= 2:
            score += 0.15
            indicators.append("具有地理适应性")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _assess_leadership_potential(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估领导潜力"""
        score = 0.0
        indicators = []
        
        experience_text = candidate_data.get("experience", "")
        
        # 基于管理经验
        leadership_keywords = ["领导", "管理", "带队", "负责", "主导", "组织"]
        leadership_mentions = sum(1 for keyword in leadership_keywords if keyword in experience_text)
        
        if leadership_mentions >= 3:
            score += 0.4
            indicators.append("具有明确的领导经验")
        elif leadership_mentions >= 1:
            score += 0.2
            indicators.append("有一定的领导经历")
        
        # 基于项目规模
        if "团队" in experience_text:
            if "10人" in experience_text or "十人" in experience_text:
                score += 0.3
                indicators.append("管理过中等规模团队")
            elif "5人" in experience_text or "五人" in experience_text:
                score += 0.2
                indicators.append("管理过小团队")
        
        # 基于影响力指标
        impact_keywords = ["优化", "提升", "改进", "创新", "解决"]
        impact_count = sum(1 for keyword in impact_keywords if keyword in experience_text)
        
        if impact_count >= 3:
            score += 0.2
            indicators.append("具有业务影响力")
        
        # 基于沟通协调能力
        communication_keywords = ["协调", "沟通", "合作", "跨部门"]
        comm_count = sum(1 for keyword in communication_keywords if keyword in experience_text)
        
        if comm_count >= 2:
            score += 0.1
            indicators.append("具备协调沟通能力")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _assess_technical_depth(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估技术深度"""
        score = 0.0
        indicators = []
        
        experience_text = candidate_data.get("experience", "")
        skills = candidate_data.get("skills", [])
        
        # 基于专业技能深度
        expert_keywords = ["专家", "架构师", "高级", "资深", "senior"]
        expert_level = sum(1 for keyword in expert_keywords if keyword in experience_text)
        
        if expert_level >= 2:
            score += 0.3
            indicators.append("具有专家级技术水平")
        elif expert_level >= 1:
            score += 0.2
            indicators.append("达到高级技术水平")
        
        # 基于技术广度与深度平衡
        if len(skills) >= 8:
            score += 0.25
            indicators.append("技术栈覆盖全面")
        
        # 基于核心技术掌握程度
        core_tech_keywords = ["架构", "设计模式", "性能优化", "系统设计"]
        core_tech_count = sum(1 for keyword in core_tech_keywords if keyword in experience_text)
        
        if core_tech_count >= 2:
            score += 0.25
            indicators.append("掌握核心技术概念")
        
        # 基于技术创新
        if "开源" in experience_text or "专利" in experience_text:
            score += 0.15
            indicators.append("具有技术创新贡献")
        
        # 基于解决复杂问题的能力
        complex_keywords = ["解决", "优化", "重构", "迁移"]
        complex_count = sum(1 for keyword in complex_keywords if keyword in experience_text)
        
        if complex_count >= 2:
            score += 0.15
            indicators.append("擅长解决复杂技术问题")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _assess_innovation_capacity(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估创新能力"""
        score = 0.0
        indicators = []
        
        experience_text = candidate_data.get("experience", "")
        
        # 基于创新项目经验
        innovation_keywords = ["创新", "发明", "首创", "原创", "开发"]
        innovation_count = sum(1 for keyword in innovation_keywords if keyword in experience_text)
        
        if innovation_count >= 3:
            score += 0.4
            indicators.append("具有丰富的创新项目经验")
        elif innovation_count >= 1:
            score += 0.2
            indicators.append("参与过创新项目")
        
        # 基于技术前瞻性
        emerging_tech = ["AI", "区块链", "物联网", "VR", "AR", "边缘计算"]
        emerging_count = sum(1 for tech in emerging_tech if tech in experience_text)
        
        if emerging_count >= 2:
            score += 0.3
            indicators.append("关注前沿技术发展")
        
        # 基于问题解决创造性
        creative_keywords = ["创造性", "独特", "新颖", "突破"]
        creative_count = sum(1 for keyword in creative_keywords if keyword in experience_text)
        
        if creative_count >= 1:
            score += 0.2
            indicators.append("具有创造性思维")
        
        # 基于学术/开源贡献
        if "论文" in experience_text or "开源" in experience_text:
            score += 0.1
            indicators.append("有学术或开源贡献")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _assess_collaboration_skills(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """评估协作能力"""
        score = 0.0
        indicators = []
        
        experience_text = candidate_data.get("experience", "")
        
        # 基于团队合作经验
        team_keywords = ["团队", "协作", "合作", "配合"]
        team_count = sum(1 for keyword in team_keywords if keyword in experience_text)
        
        if team_count >= 3:
            score += 0.4
            indicators.append("具有丰富的团队协作经验")
        elif team_count >= 1:
            score += 0.2
            indicators.append("有团队合作经历")
        
        # 基于跨部门协作
        cross_dept_keywords = ["跨部门", "跨团队", "产品", "设计", "测试"]
        cross_count = sum(1 for keyword in cross_dept_keywords if keyword in experience_text)
        
        if cross_count >= 2:
            score += 0.3
            indicators.append("具有跨部门协作能力")
        
        # 基于沟通能力
        comm_keywords = ["沟通", "交流", "汇报", "演示"]
        comm_count = sum(1 for keyword in comm_keywords if keyword in experience_text)
        
        if comm_count >= 2:
            score += 0.2
            indicators.append("具备良好的沟通能力")
        
        # 基于导师/培训经验
        mentoring_keywords = ["指导", "培训", "分享", "教学"]
        mentoring_count = sum(1 for keyword in mentoring_keywords if keyword in experience_text)
        
        if mentoring_count >= 1:
            score += 0.1
            indicators.append("具有指导和分享经验")
        
        return {
            "score": min(1.0, score),
            "indicators": indicators
        }
    
    async def _predict_career_trajectories(self, candidate_data: Dict[str, Any], 
                                         potential_dimensions: List[PotentialDimension],
                                         timeframe: str) -> List[CareerTrajectory]:
        """预测职业轨迹"""
        trajectories = []
        
        # 计算各个发展路径的适合度
        path_scores = {}
        
        # 技术专家路径
        tech_expert_score = (
            self._get_dimension_score(potential_dimensions, "technical_depth") * 0.4 +
            self._get_dimension_score(potential_dimensions, "innovation_capacity") * 0.3 +
            self._get_dimension_score(potential_dimensions, "learning_ability") * 0.3
        )
        path_scores["technical_expert"] = tech_expert_score
        
        # 技术管理路径
        tech_leader_score = (
            self._get_dimension_score(potential_dimensions, "leadership_potential") * 0.4 +
            self._get_dimension_score(potential_dimensions, "collaboration_skills") * 0.3 +
            self._get_dimension_score(potential_dimensions, "technical_depth") * 0.3
        )
        path_scores["tech_leader"] = tech_leader_score
        
        # 产品技术路径
        product_score = (
            self._get_dimension_score(potential_dimensions, "adaptability") * 0.3 +
            self._get_dimension_score(potential_dimensions, "collaboration_skills") * 0.3 +
            self._get_dimension_score(potential_dimensions, "innovation_capacity") * 0.4
        )
        path_scores["product_oriented"] = product_score
        
        # 创新驱动路径
        innovation_score = (
            self._get_dimension_score(potential_dimensions, "innovation_capacity") * 0.5 +
            self._get_dimension_score(potential_dimensions, "learning_ability") * 0.3 +
            self._get_dimension_score(potential_dimensions, "technical_depth") * 0.2
        )
        path_scores["innovation_driver"] = innovation_score
        
        # 根据评分生成轨迹
        for path_id, score in sorted(path_scores.items(), key=lambda x: x[1], reverse=True):
            if score > 0.6:  # 只推荐高匹配度的路径
                path_info = self.career_paths[path_id]
                
                trajectory = CareerTrajectory(
                    timeline=self._get_timeline_by_timeframe(timeframe),
                    predicted_role=path_info["milestones"][-1],
                    probability=min(0.95, score),
                    key_milestones=path_info["milestones"],
                    required_skills=path_info["required_skills"]
                )
                
                trajectories.append(trajectory)
        
        return trajectories[:3]  # 返回前3个最匹配的路径
    
    def _get_dimension_score(self, dimensions: List[PotentialDimension], dimension_name: str) -> float:
        """获取指定维度的分数"""
        for dim in dimensions:
            if dim.name == dimension_name:
                return dim.score
        return 0.0
    
    def _get_timeline_by_timeframe(self, timeframe: str) -> str:
        """根据时间范围获取时间线"""
        if timeframe == "short_term":
            return "1-2年"
        elif timeframe == "medium_term":
            return "3-5年"
        else:  # long_term
            return "5-10年"
    
    async def _predict_growth_speed(self, candidate_data: Dict[str, Any], 
                                  potential_dimensions: List[PotentialDimension]) -> Dict[str, Any]:
        """预测成长速度"""
        
        # 基于学习能力和适应性预测成长速度
        learning_score = self._get_dimension_score(potential_dimensions, "learning_ability")
        adaptability_score = self._get_dimension_score(potential_dimensions, "adaptability")
        
        growth_rate = (learning_score * 0.6 + adaptability_score * 0.4)
        
        if growth_rate >= 0.8:
            speed_category = "快速成长"
            description = "预期快速适应新角色，12-18个月内显著提升"
        elif growth_rate >= 0.6:
            speed_category = "稳步成长"
            description = "预期稳定发展，2-3年内达到成熟水平"
        else:
            speed_category = "渐进成长"
            description = "需要更多时间和指导，3-5年内逐步提升"
        
        return {
            "growth_rate": growth_rate * 100,
            "speed_category": speed_category,
            "description": description,
            "key_accelerators": self._identify_growth_accelerators(potential_dimensions),
            "potential_barriers": self._identify_growth_barriers(potential_dimensions)
        }
    
    def _identify_growth_accelerators(self, dimensions: List[PotentialDimension]) -> List[str]:
        """识别成长加速器"""
        accelerators = []
        
        if self._get_dimension_score(dimensions, "learning_ability") >= 0.7:
            accelerators.append("强学习能力")
        
        if self._get_dimension_score(dimensions, "adaptability") >= 0.7:
            accelerators.append("高适应性")
        
        if self._get_dimension_score(dimensions, "innovation_capacity") >= 0.7:
            accelerators.append("创新思维")
        
        if self._get_dimension_score(dimensions, "collaboration_skills") >= 0.7:
            accelerators.append("优秀协作能力")
        
        return accelerators
    
    def _identify_growth_barriers(self, dimensions: List[PotentialDimension]) -> List[str]:
        """识别成长障碍"""
        barriers = []
        
        if self._get_dimension_score(dimensions, "technical_depth") < 0.5:
            barriers.append("技术深度不足")
        
        if self._get_dimension_score(dimensions, "leadership_potential") < 0.5:
            barriers.append("领导力有待培养")
        
        if self._get_dimension_score(dimensions, "collaboration_skills") < 0.5:
            barriers.append("团队协作能力需提升")
        
        return barriers
    
    async def _analyze_risk_factors(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析风险因素"""
        risk_factors = []
        risk_level = "低"
        
        # 频繁跳槽风险
        companies = candidate_data.get("companies", [])
        experience_years = candidate_data.get("experience_years", 0)
        
        if len(companies) > 3 and experience_years < 6:
            risk_factors.append("频繁跳槽历史")
            risk_level = "中"
        
        # 技能过时风险
        skills = candidate_data.get("skills", [])
        outdated_tech = ["JSP", "Struts", "Flash", "Silverlight"]
        outdated_count = sum(1 for tech in outdated_tech if tech in skills)
        
        if outdated_count > 0:
            risk_factors.append("技术栈部分过时")
        
        # 学习停滞风险
        recent_learning = candidate_data.get("recent_learning", [])
        if not recent_learning:
            risk_factors.append("缺乏持续学习证据")
        
        # 综合风险评估
        if len(risk_factors) >= 3:
            risk_level = "高"
        elif len(risk_factors) >= 1:
            risk_level = "中"
        
        return {
            "risk_level": risk_level,
            "risk_factors": risk_factors,
            "mitigation_suggestions": self._generate_risk_mitigation(risk_factors)
        }
    
    def _generate_risk_mitigation(self, risk_factors: List[str]) -> List[str]:
        """生成风险缓解建议"""
        suggestions = []
        
        for factor in risk_factors:
            if "跳槽" in factor:
                suggestions.append("提供明确的职业发展路径和成长空间")
            elif "技术栈" in factor:
                suggestions.append("安排现代技术培训和项目实践")
            elif "学习" in factor:
                suggestions.append("建立学习激励机制和成长计划")
        
        return suggestions
    
    async def _generate_development_recommendations(self, 
                                                 potential_dimensions: List[PotentialDimension],
                                                 career_trajectories: List[CareerTrajectory]) -> Dict[str, Any]:
        """生成发展建议"""
        
        # 识别需要提升的维度
        improvement_areas = []
        for dim in potential_dimensions:
            if dim.score < 0.7:
                improvement_areas.append({
                    "dimension": dim.name,
                    "current_score": dim.score * 100,
                    "target_score": 80,
                    "priority": "高" if dim.score < 0.5 else "中"
                })
        
        # 基于职业轨迹生成技能发展建议
        skill_development = []
        if career_trajectories:
            primary_path = career_trajectories[0]
            for skill in primary_path.required_skills:
                skill_development.append({
                    "skill": skill,
                    "development_method": self._suggest_development_method(skill),
                    "timeline": "6-12个月"
                })
        
        # 生成具体行动计划
        action_plan = self._create_action_plan(improvement_areas, skill_development)
        
        return {
            "improvement_areas": improvement_areas,
            "skill_development": skill_development,
            "action_plan": action_plan,
            "success_metrics": self._define_success_metrics(potential_dimensions)
        }
    
    def _suggest_development_method(self, skill: str) -> str:
        """建议技能发展方法"""
        method_map = {
            "深度技术专长": "参与核心技术项目，进行深度钻研",
            "系统设计能力": "学习架构设计，参与系统重构项目",
            "团队管理": "担任小组负责人，参加管理培训",
            "技术决策": "参与技术选型和架构评审",
            "产品思维": "与产品团队密切合作，了解业务需求",
            "创新思维": "参与创新项目，关注前沿技术发展"
        }
        return method_map.get(skill, "通过实践和学习逐步提升")
    
    def _create_action_plan(self, improvement_areas: List[Dict], skill_development: List[Dict]) -> Dict[str, List[str]]:
        """创建行动计划"""
        return {
            "短期目标(3-6个月)": [
                "完成基础技能评估和培训",
                "参与至少一个核心项目",
                "建立学习和反馈机制"
            ],
            "中期目标(6-12个月)": [
                "在关键能力维度达到目标分数",
                "承担更多责任和挑战",
                "获得相关认证或培训"
            ],
            "长期目标(1-2年)": [
                "在预测的职业轨迹上取得关键进展",
                "成为某个领域的专家或领导者",
                "为团队和组织创造显著价值"
            ]
        }
    
    def _define_success_metrics(self, dimensions: List[PotentialDimension]) -> List[Dict[str, Any]]:
        """定义成功指标"""
        metrics = []
        
        for dim in dimensions:
            if dim.score < 0.7:
                metrics.append({
                    "metric": f"{dim.description}评分",
                    "current_value": f"{dim.score * 100:.1f}分",
                    "target_value": f"{max(80, dim.score * 100 + 20):.1f}分",
                    "measurement_method": "定期评估和360度反馈"
                })
        
        return metrics
    
    async def _calculate_overall_potential(self, dimensions: List[PotentialDimension]) -> Dict[str, Any]:
        """计算综合潜力评分"""
        
        weighted_score = sum(dim.score * dim.weight for dim in dimensions)
        
        # 确定潜力等级
        if weighted_score >= 0.8:
            potential_level = "高潜力"
            description = "具有卓越的发展潜力，建议重点培养"
        elif weighted_score >= 0.6:
            potential_level = "中等潜力"
            description = "具有良好的发展前景，适合稳步培养"
        else:
            potential_level = "待开发潜力"
            description = "需要针对性培养和指导"
        
        return {
            "overall_score": weighted_score * 100,
            "potential_level": potential_level,
            "description": description,
            "top_strengths": self._identify_top_strengths(dimensions),
            "development_priorities": self._identify_development_priorities(dimensions)
        }
    
    def _identify_top_strengths(self, dimensions: List[PotentialDimension]) -> List[str]:
        """识别主要优势"""
        return [dim.name for dim in sorted(dimensions, key=lambda x: x.score, reverse=True)[:3]]
    
    def _identify_development_priorities(self, dimensions: List[PotentialDimension]) -> List[str]:
        """识别发展重点"""
        return [dim.name for dim in sorted(dimensions, key=lambda x: x.score)[:2]]
    
    async def _calculate_confidence_level(self, candidate_data: Dict[str, Any]) -> float:
        """计算预测置信度"""
        # 基于数据完整性和质量计算置信度
        data_quality_score = 0.0
        
        # 基础信息完整性
        basic_fields = ["experience", "skills", "education"]
        complete_fields = sum(1 for field in basic_fields if candidate_data.get(field))
        data_quality_score += (complete_fields / len(basic_fields)) * 0.4
        
        # 经验描述详细程度
        experience_length = len(candidate_data.get("experience", ""))
        if experience_length > 500:
            data_quality_score += 0.3
        elif experience_length > 200:
            data_quality_score += 0.2
        
        # 技能数量
        skills_count = len(candidate_data.get("skills", []))
        if skills_count >= 8:
            data_quality_score += 0.3
        elif skills_count >= 4:
            data_quality_score += 0.2
        
        return min(0.95, data_quality_score)


class PotentialPredictorAgent(AgentInterface):
    """潜力预测专家智能体"""
    
    def __init__(self):
        self.agent_id = "potential_predictor"
        self.name = "潜力预测专家"
        self.description = "基于AI模型预测候选人职业发展潜力和成长轨迹的专家"
        self.tools = [PotentialPredictionTool()]
        self.capabilities = [
            "multi_dimensional_potential_analysis",
            "career_trajectory_prediction",
            "growth_speed_assessment",
            "risk_factor_analysis",
            "development_recommendation_generation"
        ]
    
    async def process_task(self, task: Task) -> Task:
        """处理潜力预测任务"""
        try:
            task.status = TaskStatus.IN_PROGRESS
            
            # 从任务中提取候选人数据
            candidate_data = task.metadata.get("candidate_data", {})
            if not candidate_data:
                # 从描述中解析候选人信息
                candidate_data = await self._parse_candidate_info(task.description)
            
            timeframe = task.metadata.get("prediction_timeframe", "medium_term")
            focus_areas = task.metadata.get("focus_areas", ["all"])
            
            # 执行潜力预测
            prediction_tool = self.tools[0]
            prediction_result = await prediction_tool.execute({
                "candidate_data": candidate_data,
                "timeframe": timeframe,
                "focus_areas": focus_areas
            })
            
            # 生成综合预测报告
            comprehensive_report = await self._generate_comprehensive_report(
                prediction_result, task.metadata
            )
            
            task.result = comprehensive_report
            task.status = TaskStatus.COMPLETED
            
        except Exception as e:
            task.result = {"error": f"Potential prediction failed: {str(e)}"}
            task.status = TaskStatus.FAILED
        
        return task
    
    async def _parse_candidate_info(self, description: str) -> Dict[str, Any]:
        """从描述中解析候选人信息"""
        # 简化的信息解析
        candidate_data = {
            "experience": description,
            "skills": [],
            "education": "",
            "experience_years": 0
        }
        
        # 提取技能信息
        common_skills = ["Python", "Java", "JavaScript", "React", "Vue", "Django", "Spring", "MySQL", "Redis"]
        candidate_data["skills"] = [skill for skill in common_skills if skill in description]
        
        # 提取经验年限
        import re
        year_match = re.search(r'(\d+)年', description)
        if year_match:
            candidate_data["experience_years"] = int(year_match.group(1))
        
        return candidate_data
    
    async def _generate_comprehensive_report(self, prediction_result: Dict[str, Any], 
                                           metadata: Dict[str, Any]) -> Dict[str, Any]:
        """生成综合预测报告"""
        
        candidate_name = metadata.get("candidate_name", "Unknown")
        target_position = metadata.get("target_position", "Developer")
        
        # 生成执行摘要
        executive_summary = await self._create_executive_summary(prediction_result)
        
        # 生成招聘建议
        hiring_recommendation = await self._create_hiring_recommendation(prediction_result)
        
        comprehensive_report = {
            "report_meta": {
                "candidate_name": candidate_name,
                "target_position": target_position,
                "prediction_date": datetime.now().isoformat(),
                "report_version": "1.0"
            },
            "executive_summary": executive_summary,
            "detailed_prediction": prediction_result,
            "hiring_recommendation": hiring_recommendation,
            "next_steps": await self._suggest_next_steps(prediction_result)
        }
        
        return comprehensive_report
    
    async def _create_executive_summary(self, prediction_result: Dict[str, Any]) -> Dict[str, Any]:
        """创建执行摘要"""
        overall_potential = prediction_result.get("overall_potential", {})
        career_trajectories = prediction_result.get("career_trajectories", [])
        
        summary = {
            "overall_assessment": overall_potential.get("description", ""),
            "potential_score": overall_potential.get("overall_score", 0),
            "key_strengths": overall_potential.get("top_strengths", [])[:2],
            "primary_career_path": career_trajectories[0].get("predicted_role", "") if career_trajectories else "",
            "growth_outlook": prediction_result.get("growth_prediction", {}).get("speed_category", ""),
            "confidence_level": prediction_result.get("confidence_level", 0) * 100
        }
        
        return summary
    
    async def _create_hiring_recommendation(self, prediction_result: Dict[str, Any]) -> Dict[str, Any]:
        """创建招聘建议"""
        overall_score = prediction_result.get("overall_potential", {}).get("overall_score", 0)
        risk_level = prediction_result.get("risk_factors", {}).get("risk_level", "中")
        
        if overall_score >= 80 and risk_level == "低":
            recommendation = "强烈推荐"
            reasoning = "高潜力候选人，风险可控"
        elif overall_score >= 70 and risk_level in ["低", "中"]:
            recommendation = "推荐"
            reasoning = "良好潜力，适合培养"
        elif overall_score >= 60:
            recommendation = "谨慎考虑"
            reasoning = "中等潜力，需要评估培养成本"
        else:
            recommendation = "不推荐"
            reasoning = "潜力有限，不适合当前岗位"
        
        return {
            "recommendation": recommendation,
            "reasoning": reasoning,
            "conditions": self._get_hiring_conditions(overall_score, risk_level),
            "expected_roi": self._calculate_expected_roi(prediction_result)
        }
    
    def _get_hiring_conditions(self, score: float, risk_level: str) -> List[str]:
        """获取招聘条件"""
        conditions = []
        
        if score < 70:
            conditions.append("需要详细的培训计划")
        
        if risk_level == "高":
            conditions.append("需要额外的保留措施")
        
        if score >= 80:
            conditions.append("可以委以重任")
        
        return conditions
    
    def _calculate_expected_roi(self, prediction_result: Dict[str, Any]) -> Dict[str, Any]:
        """计算预期投资回报"""
        growth_rate = prediction_result.get("growth_prediction", {}).get("growth_rate", 0)
        
        if growth_rate >= 80:
            roi_category = "高回报"
            payback_period = "6-12个月"
        elif growth_rate >= 60:
            roi_category = "中等回报"
            payback_period = "12-18个月"
        else:
            roi_category = "长期回报"
            payback_period = "18-24个月"
        
        return {
            "roi_category": roi_category,
            "expected_payback_period": payback_period,
            "investment_level": "标准培训投入" if growth_rate >= 60 else "高强度培训投入"
        }
    
    async def _suggest_next_steps(self, prediction_result: Dict[str, Any]) -> List[str]:
        """建议后续步骤"""
        next_steps = []
        
        overall_score = prediction_result.get("overall_potential", {}).get("overall_score", 0)
        
        if overall_score >= 70:
            next_steps.extend([
                "安排技术深度面试",
                "进行团队文化匹配评估",
                "制定个性化发展计划"
            ])
        else:
            next_steps.extend([
                "进行基础技能补充评估",
                "评估培训投入成本",
                "考虑实习或试用期安排"
            ])
        
        next_steps.append("定期跟踪和评估发展进展")
        
        return next_steps
    
    async def get_capabilities(self) -> List[str]:
        """获取智能体能力"""
        return self.capabilities
    
    async def get_status(self) -> Dict[str, Any]:
        """获取智能体状态"""
        return {
            "agent_id": self.agent_id,
            "name": self.name,
            "status": "active",
            "prediction_models": ["multi_dimensional_analysis", "career_trajectory", "growth_assessment"],
            "capabilities": self.capabilities
        }